package com.xinqiupark.technology.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.xinqiupark.technology.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class JsoupActivity extends AppCompatActivity {

    @BindView(R.id.tv_content)
    TextView mTvContent;

    @SuppressLint("SetTextI18n")
    @OnClick(R.id.btn_jsoup)
    public void onJsoupClick() {
        new Thread(() -> {
            try {
                //从一个url中获取Document对象
                Document document = Jsoup.
                        connect("http://home.meishichina.com/show-top-type-recipe.html")
                        .get();

                //选择节点
                Elements elements = document.select("div.top-bar");
                final int size =
                        elements.size();

                runOnUiThread(() -> {
                    //打印 <a>标签里面的title
                    mTvContent.setText(size + "" + elements.select("a").attr("title"));
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    @OnClick(R.id.btn_Jsoup2)
    public void onJsoup2Click() {
        new Thread(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect("http://home.meishichina.com/show-top-type-recipe.html").get();
                    final Elements titleAndPic = doc.select("div.pic");

                    //使用Element.select(String selector)查找元素，使用Node.attr(String key)方法取得一个属性的值
                    Log.i("mytag", "title:" + titleAndPic.get(1).select("a").attr("title") + "pic:" + titleAndPic.get(1).select("a").select("img").attr("data-src"));

                    //所需链接在<div class="detail">中的<a>标签里面
                    Elements url = doc.select("div.detail").select("a");
                    Log.i("mytag", "url:" + url.get(1).attr("href"));

                    //原料在<p class="subcontent">中
                    Elements burden = doc.select("p.subcontent");
                    runOnUiThread(() -> {
                        //对于一个元素中的文本，可以使用Element.text()方法
                        mTvContent.setText("burden:" + burden.get(1).text());
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsoup);
        ButterKnife.bind(this);
    }
}
